﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using COC.Sound;

namespace COC.GameLogic
{
	class WeaponActor : AnimActor
	{
		protected PlayerActor m_owner;
		protected Texture2D[] m_GunFireTextures;
		protected float m_TimeToShowGunFire = -1;

		public WeaponActor(string name, string modelName, PlayerActor owner,
			int maxHp, int attack, float speed)
			: base(name, modelName)
		{
			m_owner = owner;
			m_GunFireTextures = new Texture2D[8];
			for (int i = 0; i < 8; i++)
			{
				m_GunFireTextures[i] = CoCGame.Singleton.Content.Load<Texture2D>(
					@"Textures/Fire/flame" + (i + 1).ToString());
			}
		}

		public bool Update(GameTime gameTime)
		{
			if (m_Diposed)
			{
				return false;
			}

			Matrix parentMat = Matrix.Identity;

			for (int i = 0; i < m_owner.Model.SkeletonBones.Count; i++)
			{
				if (m_owner.Model.SkeletonBones[i].Name == "R_Hand")
				{
					parentMat = m_owner.Character.AnimController.SkinnedBoneTransforms[i];
				}
			}

			Matrix ltow = Matrix.CreateFromYawPitchRoll(m_Rotation.Y, m_Rotation.X, m_Rotation.Z)
				* Matrix.CreateTranslation(m_Position) * parentMat;

			m_ActorCharacter.AnimController.Update(gameTime.ElapsedGameTime, ltow);
			m_LocalToWorldMat = ltow;

			if (m_TimeToShowGunFire > 0)
			{
				m_TimeToShowGunFire -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;
				int texIndex = (int)(m_TimeToShowGunFire / 13);
				if (texIndex < 0) texIndex = 0;
				if (texIndex > m_GunFireTextures.Length - 1) texIndex = m_GunFireTextures.Length - 1;
				
				//枪口朝向的方向
				Vector3 muzzleDir = Vector3.Normalize(new Vector3(-0.8f, -1.2f, 0.6f));
				Vector3 vToward = Vector3.TransformNormal(muzzleDir, ltow);

				//枪口位置
				Vector3 muzzle = Vector3.Transform(
					new Vector3(-3.55f, 2.5f, 2.0f) + muzzleDir * 1.5f, ltow);
				
				Vector3 dir = muzzle - CoCGame.Singleton.GameCamera.Position;
				Vector3 vSide = Vector3.Normalize(Vector3.Cross(vToward, dir));
				CoCGame.Singleton.CurrentGameWorld.m_BillBoard.DrawBillBoardAxisAligned(
					muzzle, new Vector2(1, 2), m_GunFireTextures[texIndex],
					-vSide,
					vToward);
			}

			return true;
		}

		public void DoAction(string action)
		{
		}

		public void Attack(int damage)
		{
			SoundManager.PlaySound("GunShoot");
			m_TimeToShowGunFire = 150;
			Ray ray = new Ray(CoCGame.Singleton.GameCamera.Position, CoCGame.Singleton.GameCamera.Direction);
			string rslt = CoCGame.Singleton.CurrentGameWorld.m_ShootDetecter.TestShootImmediate(ray, damage);
			if(rslt != null)
			{
				CoCGame.Singleton.Console.WriteLine(rslt);
			}
		}
	}
}